package raceReservationServer.saxParser;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;

public class RaceServerGatewaysSAXHandler extends DefaultHandler{
	private List<GatewayObject> gObjects;
	private String texto;

	//============================================================================
	// Métodos de DefaultHandler y pertenecimientes a ContentHandler sobreescritos
	//============================================================================

	public void startDocument() throws SAXException {
		System.out.println("# Comenzando el parseo del documento...");
		this.gObjects = new ArrayList<GatewayObject>();	
		texto="";
	}

	public void endDocument() throws SAXException {
		System.out.println("# Parseo del documento finalizado.");
	}

	public void startElement(String namespaceURI, String lName, // local name
			String qName, // qualified name
			Attributes attrs) throws SAXException {

		System.out.println(" * [Etiqueta] -> <" + qName + ">");

		if (qName.equals("gateway")) {
			GatewayObject gObj=new GatewayObject();
			gObj.setName(attrs.getValue("name"));
			System.out.println("    - [Atribute] -> name= '"
					+ attrs.getValue("name") + "'");
			gObj.setUrl(attrs.getValue("url"));
			System.out.println("    - [Atribute] -> url= '"
					+ attrs.getValue("url") + "'");
			gObj.setPort(attrs.getValue("port"));
			System.out.println("    - [Atribute] -> port= '"
					+ attrs.getValue("port") + "'");
			gObj.setTech(attrs.getValue("tech"));
			System.out.println("    - [Atribute] -> tech= '"
					+ attrs.getValue("tech") + "'");
			this.gObjects.add(gObj);
		}
	}
	
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String s = String.valueOf(ch, start, length).trim();
		this.texto += s;
	}

	public void processingInstruction(String target, String data)
			throws SAXException {
		System.out.println(" * [PI] -> <?" + target + data + "?>");
	}

	//============================================================================
	// Métodos de DefaultHandler y pertenecimientes a ErrorHandler sobreescritos
	//============================================================================

	public void error(SAXParseException exception) throws SAXException {
		System.out.println("# [ERROR] -> " + exception.getMessage());
	}

	public void warning(SAXParseException exception) throws SAXException {
		System.out.println("# [WARNING] -> " + exception.getMessage());
	}

	public void fatalError(SAXParseException exception) throws SAXException {
		System.out.println("# [FATAL ERROR] -> " + exception.getMessage());
	}

	//================
	// Métodos propios
	//================
	public List<GatewayObject> getGateway() {
		return this.gObjects;
	}
}